<template>
  <div class="form-conf">
    <v-form-render :form-json="newFormData" ref="vFormRef"></v-form-render>
    <div class="dialog-footer">
      <el-button type="info" icon="el-icon-circle-plus-outline" :loading="Addloading" @click="submitAdd">暂存</el-button>
      <el-button type="primary" icon="el-icon-circle-check" :loading="submitloading" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script>
import { getProcessForm, startProcess, getProcessFormHold } from '@/api/workflow/process'

export default {
  name: 'VformRenderDialog',
  props: {
    formData: {
      type: Object,
      required: true
    },
    definitionId: {
      type: String,
      required: true
    },
    businessKey: {
      type: String,
      required: false
    },
    code: {
      type: String,
      required: true
    },
    ioType: {
      type: Number
    },
    budget: {
      type: Object,
      required: false
    },
    hisAmount: {
      type: Object,
      require:false
    }
  },
  data() {
    return {
      Addloading: false,
      submitloading: false,
      newFormData:this.formData,
    }
  },
  computed: {
    _userInfo() {
      return this.$store.state.user.userInfo
    }
  },
  created() {
    // console.log(JSON.stringify(this.formData), '77777777')
    // 解决大于小于符号被转译的问题
    const FormJson = JSON.stringify(JSON.stringify(this.formData)) 
    let newFormJson = null
    newFormJson = FormJson.replace('&gt;','>')
    newFormJson = newFormJson.replace('&lt;','<')
    // console.log(newFormJson, '新的');
    this.newFormData = JSON.parse(JSON.parse(newFormJson))
  },
  mounted() {
    this.userInfo()
    // console.log(this.ioType, '进出类型，，，，，，，，，，，，，')

  },
  methods: {
    userInfo() {
      this.$refs.vFormRef.setFieldValue('nickName', this._userInfo.nickName)
      this.$refs.vFormRef.setFieldValue('deptName', this._userInfo.dept.deptName)
      this.$refs.vFormRef.setFieldValue('role', this._userInfo.roles[0].roleName)
      this.$refs.vFormRef.setFieldValue('newDate', this.$moment().format('YYYY-MM-DD'))
      if (this.$refs.vFormRef.getWidgetRef('phonenumber')) {
        this.$refs.vFormRef.setFieldValue('phonenumber', this._userInfo.phonenumber)
      }
      if (this.$refs.vFormRef.getWidgetRef('budgetProjectCode')) {
        this.$refs.vFormRef.setFieldValue('budgetProjectCode', this.budget.budgetProjectCode)
      }
      if (this.$refs.vFormRef.getWidgetRef('budgetProjectName')) {
        this.$refs.vFormRef.setFieldValue('budgetProjectName', this.budget.budgetProjectName)
      }
      if (this.$refs.vFormRef.getWidgetRef('category')) {
        this.$refs.vFormRef.setFieldValue('category', this.budget.category)
      }
      if (this.$refs.vFormRef.getWidgetRef('classify')) {
        this.$refs.vFormRef.setFieldValue('classify', this.budget.classify)
      }
      if (this.$refs.vFormRef.getWidgetRef('executingDepartment')) {
        this.$refs.vFormRef.setFieldValue('executingDepartment', this.budget.department)
      }
      if (this.$refs.vFormRef.getWidgetRef('budgetTotalAmount')) {
        this.$refs.vFormRef.setFieldValue('budgetTotalAmount', this.budget.budget)
      }
      // 历史执行金额只读和获取值
      if (JSON.stringify(this.hisAmount) != "{}") {
        const historicalExecutionAmount = this.$refs.vFormRef.getWidgetRef('historicalExecutionAmount')
        const budgetTotalAmount = this.$refs.vFormRef.getWidgetRef('budgetTotalAmount')
        const budgetBalance = this.$refs.vFormRef.getWidgetRef('budgetBalance')
        const currentExecutionAmount = this.$refs.vFormRef.getWidgetRef('currentExecutionAmount')
        console.log(currentExecutionAmount,'8888888888888888888');
        if (historicalExecutionAmount && budgetTotalAmount && budgetBalance ) {
          historicalExecutionAmount.setReadonly(true)
          budgetTotalAmount.setReadonly(true)
          budgetBalance.setReadonly(true)
          this.$refs.vFormRef.setFieldValue('historicalExecutionAmount', this.hisAmount.historical)
          const historical = parseFloat(historicalExecutionAmount.getValue())
          const TotalAmount = parseFloat(budgetTotalAmount.getValue())
          const decimalPlaces = (TotalAmount.toString().split('.')[1] || '').length;
          const count = (TotalAmount - historical).toFixed(decimalPlaces)
          budgetBalance.setValue(count)
          console.log(count,'金额');
          
        }
      }
      
    },
    // 暂存表单
    submitAdd() {
      let obj = this.$refs.vFormRef.getFormData(false)
      this.Addloading = true
      obj.ioType = this.ioType
      obj.BUSINESS_KEY=this.businessKey
      //   .then(formData => {
      getProcessFormHold(this.definitionId, JSON.stringify(obj), this.code).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess('暂存成功')
          this.Addloading = false
          this.$emit('vformDialog')
          //   this.$tab.closeOpenPage({
          //     path: "/work/own"
          //   });
        }
      })
      // });
    },
    // 提交表单按钮
    submitForm() {
      // 校验表单
      this.$refs['vFormRef'].validateForm(valid => {
        // 获取切换框的值
        const val = this.$refs.vFormRef.getFieldValue('cut')
        // 判断是否有切换表单
        if (val.length !== 0) {
          if (val == 1) {
            if (valid) {
              // 当前展示表单校验通过
              this.validForm = true
              // 赋值给切换框
              this.$refs.vFormRef.setFieldValue('cut', 2)
              // 再次校验当前表单
              this.$refs['vFormRef'].validateForm(validl => {
                if (validl) {
                  // 当前表单二校验通过
                  // console.log("1");
                  this.validForm2 = true
                  this.cutForm()
                }
              })
            }
          } else if (val == 2) {
            // 如果表单二展示
            if (valid) {
              // 校验通过
              this.validForm2 = true
              // 赋值给切换框
              // this.$nextTick(() => {
              this.$refs.vFormRef.setFieldValue('cut', 1)
              // })
              // 再次校验当前展示表单
              this.$refs['vFormRef'].validateForm(validlS => {
                // console.log(validlS, "kan");
                if (validlS) {
                  // 校验通过
                  this.validForm = true
                  this.cutForm()
                }
              })
            }
          }
        } else {
          // console.log("不切换");
          this.$refs.vFormRef.getFormData().then(formData => {
            this.submitloading = true
            formData.ioType = this.ioType
            startProcess(this.definitionId, JSON.stringify(formData), this.code).then(
              res => {
                this.$modal.msgSuccess('操作成功')
                this.submitloading = false
                this.$emit('vformDialog')
              }
            )
          })
        }
      })
    },

    // 表单校验方法
    cutForm() {
      // console.log(this.validForm, this.validForm2, "通过");
      if (this.validForm && this.validForm2) {
        this.$refs.vFormRef.setFieldValue('cut', 1)
        this.submitloading = true
        this.$refs.vFormRef
          .getFormData()
          .then(formData => {
            formData.ioType = this.ioType
            formData.BUSINESS_KEY=this.businessKey
            startProcess(this.definitionId, JSON.stringify(formData), this.code).then(
              res => {
                this.$modal.msgSuccess('操作成功')
                this.submitloading = false
                this.$emit('vformDialog')
              }
            )
          })
          .catch(error => {
            // Form Validation failed
            this.$message.error(error)
          })
      } else {
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  margin: 15px auto;
  text-align: center;
}
</style>
